package com.liqi.frame.comm.controller.manager;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liqi.frame.comm.Constants;
import com.liqi.frame.comm.dto.DtreeDto;
import com.liqi.frame.comm.dto.HttpResult;
import com.liqi.frame.comm.dto.LayuiTableData;
import com.liqi.frame.comm.dto.ZtreeDto;
import com.liqi.frame.comm.enums.ResultEnum;
import com.liqi.frame.comm.po.Group;
import com.liqi.frame.comm.po.User;
import com.liqi.frame.comm.service.GroupService;
import com.liqi.frame.comm.token.TokenUtil;
import com.liqi.frame.comm.util.IdUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 组织的ajax类
 * @author liqi on 2018/2/2.
 * liqiwork@qq.com
 */
@RestController
@RequestMapping("/groupManager/ajax")
@Api(value = "组织的相关方法", tags = {"组织的相关方法"})
public class GroupManagerAjaxController {

    /**
     * 获取组织列表
     * @param page 页号
     * @param limit 单页数据条数
     * @param groupName 组织名称
     * @return 表格数据
     */
    @ApiOperation(value="获得组织列表", notes = "通过组织名称获得组织列表", httpMethod = "GET")
    @RequestMapping({"getGroupList"})
    public LayuiTableData getGroupList(@RequestBody Map params) {
        Integer page = (Integer)params.get("page");
        Integer limit = (Integer)params.get("limit");
        String groupName = params.get("groupName")+"";

        LayuiTableData result = new LayuiTableData(ResultEnum.SUCCESS);

        User user = TokenUtil.getToken();
        if (user!=null && !Objects.equals("",user.getGroupId())) {
//            Page pageParam = new Page();
//            IPage<Group> groupIPage = groupService.getGroupListWithName(groupName, user.getGroupId(), pageParam);
//
//            if (groupIPage!=null) {
//                result.setData(groupIPage.getRecords());
//                result.setCount((int)groupIPage.getTotal());
//            } else {
//                result.setCount(0);
//            }
//            result.setCode(0);
//            result.setMsg("");

            PageHelper.startPage(page, limit);
            List<Group> list = groupService.getGroupListWithName(groupName, user.getGroupId());
            if (list!=null) {
                PageInfo pageInfo = new PageInfo(list);
                result.setData(pageInfo.getList());
                result.setCount(pageInfo.getTotal());
//                List<Group> list1 = groupService.getGroupListWithName(groupName, user.getGroupId());
//                result.setCount(list1.size());
            } else {
                result.setCount(0L);
            }
            result.setCode(0);
            result.setMsg("");
        }

        return result;
    }

    @PostMapping({"getGroupList4TableTree"})
    public HttpResult getGroupList4TableTree() {
        List<Group> list = groupService.getGroupList();
        if(list!=null && list.size()>0) {
            return HttpResult.success(list);
        }
        return HttpResult.success(null);
    }

    @RequestMapping({"getGroupList4Dtree"})
    public HttpResult getGroupList4Dtree() {
        List<Group> list = groupService.getGroupList();
        List<DtreeDto> listResult = new ArrayList<>();
        for (Group groupObject:list) {
            DtreeDto dtreeDto = new DtreeDto();
            BeanUtil.copyProperties(groupObject, dtreeDto);
            dtreeDto.setTitle(groupObject.getGroupName());
            dtreeDto.setCheckArr("0");
            listResult.add(dtreeDto);
        }
        if(listResult!=null && listResult.size()>0) {
            return HttpResult.success(listResult);
        }
        return HttpResult.success(null);
    }

    @ApiOperation(value="获得组织对象", notes = "通过组织id获得组织对象", httpMethod = "GET")
    @RequestMapping({"getGroupById"})
    public HttpResult getGroupById(@RequestBody Map params) {
        String id = params.get("id")+"";
        Group group = groupService.getGroupById(id);
        HttpResult result = new HttpResult(ResultEnum.SUCCESS);
        result.setData(group);
        return result;
    }

    @ApiOperation(value="保存组织信息", notes = "保存组织信息", httpMethod = "POST")
    @RequiresPermissions(value = {"groupManager:save",
                                "groupManager:saveRole",
            Constants.OPERATION_PASSKEY}, logical = Logical.OR)
    @PostMapping({"saveGroup"})
    public HttpResult saveGroup(@RequestBody Map params) {
        String id = params.get("id")+"";
        String groupName = params.get("groupName")+"";
        String comment = params.get("comment")+"";
        Object orderIdObject = params.get("orderId");
        Float orderId = new Float(0);
        if (Objects.isNull(orderIdObject)) {
            orderId = Float.parseFloat(params.get("orderId") + "");
        }
        String parentId = params.get("parentId")+"";
        String parentName = params.get("parentName")+"";

        int resultStatus = 0;
        groupName = groupName.trim();
        comment = comment.trim();
        List groupList = groupService.getGroupListByName(groupName, parentId);
        if (groupList.size()>0) {
            boolean isHasGroupName = false;
            for (int i = 0; i < groupList.size(); i++) {
                if (!Objects.equals(((Group)groupList.get(i)).getId(), id)) {
                    isHasGroupName = true;
                    break;
                };
            }

            if (isHasGroupName) {
                return HttpResult.failure("组织名称:"+groupName+",已经存在.");
            } else {
                resultStatus = groupService.updateGroup(id, groupName, comment, orderId, parentId, parentName);
            }
        } else {
            if (id != null && !"".equals(id)) {
                resultStatus = groupService.updateGroup(id, groupName, comment, orderId, parentId, parentName);
            } else {
                resultStatus = groupService.insertGroup(IdUtil.getId() + "", groupName, comment, orderId, parentId, parentName);
            }
            if (resultStatus==0) {
                return HttpResult.failure();
            }
        }
        return HttpResult.success();
    }

    @ApiOperation(value="修改组织信息", notes = "修改组织信息", httpMethod = "POST")
    @PostMapping({"updateOrderId"})
    public HttpResult updateOrderId(@RequestBody Map params) {
        String id = params.get("id")+"";
        Object orderIdObject = params.get("orderId");
        Float orderId = new Float(0);
        if (Objects.isNull(orderIdObject)) {
            orderId = Float.parseFloat(params.get("orderId") + "");
        }

        int resultStatus = 0;
        resultStatus = groupService.updateOrderId(id, orderId);
        HttpResult result = new HttpResult(ResultEnum.SUCCESS);
        if (resultStatus==0) {
            result.setCode(ResultEnum.FAILURE.getCode());
        }
        return result;
    }

    @ApiOperation(value="删除指定组织", notes = "通过组织id删除组织", httpMethod = "POST")
    @RequiresPermissions(value = {"groupManager:delete",
            "groupManager:deleteGroup",
            Constants.OPERATION_PASSKEY}, logical = Logical.OR)
    @PostMapping({"deleteGroup"})
    public HttpResult deleteGroup(@RequestBody Map params) {
        String id = params.get("id")+"";
        int resultStatus = groupService.deleteGroupById(id);
        if (resultStatus > 0) {
            return HttpResult.success("删除成功！");
        } else {
            return HttpResult.failure("删除错误：还有子组织、账号或角色与其关联。");
        }
    }

    @ApiOperation(value="获得组织树", notes = "获得组织树", httpMethod = "GET")
    @RequestMapping({"getGroupZtree"})
    public HttpResult getGroupZtree() {
//        HttpResult result = new HttpResult(ResultEnum.SUCCESS);
        // 获取可选项
        List<Group> allGroupList = groupService.getGroupList();
        List<ZtreeDto> ztreeList = new ArrayList<ZtreeDto>();
        for (int i = 0;i<allGroupList.size();i++){
            ZtreeDto ztreeDto = new ZtreeDto();
            ztreeDto.setId(allGroupList.get(i).getId());
            ztreeDto.setpId(allGroupList.get(i).getParentId());
            ztreeDto.setName(allGroupList.get(i).getGroupName());
            ztreeList.add(ztreeDto);
        }
        return HttpResult.success(ztreeList);
    }

//    @ApiOperation(value="获得组织树", notes = "获得组织树(layui tree)", httpMethod = "GET")
//    @GetMapping({"getGroupLayuiTree"})
//    public HttpResult getGroupLayuiTree(String id) {
//        HttpResult result = new HttpResult(ResultEnum.SUCCESS);
//        // 获取可选项
//        List<Group> allGroupList = groupService.getGroupList();
//        List<ZtreeDto> ztreeList = new ArrayList<ZtreeDto>();
//        for (int i = 0;i<allGroupList.size();i++){
//            ZtreeDto ztreeDto = new ZtreeDto();
//            ztreeDto.setId(allGroupList.get(i).getId());
//            ztreeDto.setpId(allGroupList.get(i).getParentId());
//            ztreeDto.setParent(true);
//            ztreeDto.setName(allGroupList.get(i).getGroupName());
//            ztreeList.add(ztreeDto);
//        }
//        result.setData(ztreeList);
//        return result;
//    }

    @Autowired
    private GroupService groupService;
}
